const drawLine = function(coordinates, vm) {
	// 创建LineString几何对象
	const trackLineString = new ol.geom.LineString(coordinates);

	// 创建轨迹特征
	const trackFeature = new ol.Feature({
		geometry: trackLineString,
	});

	// 创建矢量源并添加轨迹特征
	const trackSource = new ol.source.Vector({
		features: [trackFeature],
	});

	// 创建矢量图层并添加到地图
	const trackLayer = new ol.layer.Vector({
		source: trackSource,
	});

	if (vm.map) {
		// const center = getCenter(coordinates)
		vm.map.getView().fit(trackFeature.getGeometry())
		vm.layers.push(trackLayer);
		vm.map.addLayer(trackLayer);
	}

	// 将自定义样式函数应用到矢量图层上
	trackLayer.setStyle(arrowInit(vm.map));
}

// 去重函数
function removeDuplicates(locations) {
	const seen = new Set();
	const uniqueLocations = [];

	for (const location of locations) {
		const key = `${location.lon},${location.lat}`;
		if (!seen.has(key)) {
			seen.add(key);
			uniqueLocations.push(location);
		}
	}

	return uniqueLocations;
}

// 自定义样式函数
function arrowInit(map) {
	return function arrowStyleFunction(feature) {
		const geometry = feature.getGeometry();
		let coordinates = geometry.getCoordinates();
		const arrowStyles = [];

		// 计算每段线段的中间点和方向角度
		for (let i = 0; i < coordinates.length - 1; i++) {
			const start = coordinates[i];
			const end = coordinates[i + 1];
			const dx = end[0] - start[0];
			const dy = end[1] - start[1];
			const angle = Math.atan2(dy, dx);

			// 计算中间点坐标
			const midX = (start[0] + end[0]) / 2;
			const midY = (start[1] + end[1]) / 2;
			const midpoint = [midX, midY];

			const zoom = map.getView().getZoom(); // 获取当前地图缩放级别
			const scale = calculateScale(zoom); // 根据缩放级别计算缩放比例

			// 创建箭头样式
			arrowStyles.push(new ol.style.Style({
				geometry: new ol.geom.Point(midpoint),
				image: new ol.style.Icon({
					src: './assets/images/arrow-icon.png', // 箭头图标路径（需要替换为实际路径）
					anchor: [0.75, 0.5], // 锚点位置（相对于图标中心）
					rotateWithView: true, // 不随视图旋转
					rotation: -angle,
					scale, // 图标缩放比例
				}),
			}));
		}

		arrowStyles.push(...[
			new ol.style.Style({
				stroke: new ol.style.Stroke({
					color: '#fff',
					width: 10,
				}),
			}),
			new ol.style.Style({
				stroke: new ol.style.Stroke({
					color: '#00ff00',
					width: 8,
				}),
			}),
		]);

		return arrowStyles;
	}
}


function calculateScale(zoom) {
	if (zoom < 13) return 0
	else return 0.2
}

const drawPic = async function([lon, lat], imgSrc, vm, infoData, isCar) {
	const image = new Image();
	image.src = imgSrc;
	image.width = isCar ? 20 : 30;

	// 方向
	if (isCar) {
		image.style = `transform:rotate(${infoData.agl||0}deg);transform-origin: center center;`
	}

	const overlay = new ol.Overlay({
		element: image,
		position: [lon, lat],
		offset: [isCar ? -10 : -15, isCar ? -31 : -36],
		autoPan: true,
	});

	// 查地址-起点
	if (!infoData.adr) {
		try {
			const {
				data
			} = await getAdressInfoByCoordinate([lon, lat])
			if (data.returnCode == 'Y' && data.obj) {
				const res = JSON.parse(data.obj);
				if (res?.data?.list?.[0]) {
					const {
						ADDRESS,
						NAME
					} = res.data.list[0]
					infoData.adr = ADDRESS + "<br>　　　" + NAME
				}
			}
		} catch (e) {
			// infoData.adr = "阿谁都不会节哀顺变的话就爱上的<br>　　　阿谁都不会节哀顺变的话"

		}
	}

	overlay.getElement().addEventListener('click', (e) => {
		if (!vm.mapInfoWindow) {
			vm.mapInfoWindow = document.createElement('div');
			vm.mapInfoWindow.id = 'mapInfoPop';
			vm.mapInfoWindow.className = 'panel el-card';
			const element = document.createElement('div');
			element.className = "panel-content";
			vm.mapInfoWindow.appendChild(element);
			//是否有关闭按钮
			const closeBtn = document.createElement('button');
			closeBtn.className = 'panel-close el-button el-button--text el-icon-close';
			closeBtn.addEventListener('click', e => {
				e.stopPropagation();
				vm.mapInfoWindow.style.display = 'none';
			});
			vm.mapInfoWindow.appendChild(closeBtn);
		}

		vm.mapInfoWindow.querySelector('.panel-content').innerHTML =
			(infoData.adr ? `<p>地址：${infoData.adr}</p>` : '') +
			(infoData.gtm ? `<p>时间：${infoData.gtm}</p>` : '');

		vm.mapInfoWindow.style.display = 'none';

		const overlayPopDiv = new ol.Overlay({
			element: vm.mapInfoWindow,
			position: [lon, lat],
			offset: [-100, isCar ? -100 : -108],
			stopEvent: false,
		});
		vm.map.addOverlay(overlayPopDiv);
		vm.mapInfoWindow.style.display = 'block';
	});

	vm.map.addOverlay(overlay);
}

const drawPos = function([lon, lat], imgSrc, vm, infoData) {
	const image = new Image();
	image.src = imgSrc;
	image.width = 20;
	// image.height = 50;

	const overlay = new ol.Overlay({
		element: image,
		position: [lon, lat],
		offset: [-10, -10],
		autoPan: true,
	});

	overlay.getElement().addEventListener('mouseover', async (e) => {
		if (!vm.mapInfoWindow) {
			vm.mapInfoWindow = document.createElement('div');
			vm.mapInfoWindow.id = 'mapInfoPop';
			vm.mapInfoWindow.className = 'panel el-card';
			const element = document.createElement('div');
			element.className = "panel-content";
			vm.mapInfoWindow.appendChild(element);
		}

		// 查地址-起点
		if (!infoData.adr) {
			try {
				const {
					data
				} = await getAdressInfoByCoordinate([lon, lat])
				if (data.returnCode == 'Y' && data.obj) {
					const res = JSON.parse(data.obj);
					if (res?.data?.list?.[0]) {
						const {
							ADDRESS,
							NAME
						} = res.data.list[0]
						infoData.adr = ADDRESS + "<br>　　　" + NAME
					}
				}
			} catch (e) {
				//TODO handle the exception
			}
		}

		vm.mapInfoWindow.querySelector('.panel-content').innerHTML =
			(infoData.adr ? `<p>地址：${infoData.adr}</p>` : '') +
			(infoData.gtm ? `<p>时间：${infoData.gtm}</p>` : '');

		vm.mapInfoWindow.style.display = 'none';

		const overlayPopDiv = new ol.Overlay({
			element: vm.mapInfoWindow,
			position: [lon, lat],
			offset: [-100, -80],
			stopEvent: false,
		});
		vm.map.addOverlay(overlayPopDiv);
		vm.mapInfoWindow.style.display = 'block';
	});

	vm.map.addOverlay(overlay);
	return overlay
}

const drawPlayPic = function([lon, lat], imgSrc, vm, infoData) {
	const image = new Image();
	image.src = imgSrc;
	image.width = 20;
	// image.height = 50;
	// 方向
	image.style = `transform:rotate(${infoData.agl||0}deg);transform-origin: center center;`

	const overlay = new ol.Overlay({
		element: image,
		position: [lon, lat],
		offset: [-10, -31],
		autoPan: true,
	});

	vm.map.addOverlay(overlay);
	return overlay
}

// 计算中心坐标
function getCenter(posArr) {
	if (posArr.length === 1) {
		return posArr[0]
	}
	const centerLongt = posArr.map(item => Number(item[0])).reduce((a, b) => a + b, 0) / posArr.length;
	const centerLtat = posArr.map(item => Number(item[1])).reduce((a, b) => a + b, 0) / posArr.length;
	return [centerLongt, centerLtat];
}

// 计算点到线段的平方距离
const squaredDistanceToSegment = function(p, a, b) {
	const ab = [b[0] - a[0], b[1] - a[1]];
	const ap = [p[0] - a[0], p[1] - a[1]];
	const t = (ab[0] * ap[0] + ab[1] * ap[1]) / (ab[0] * ab[0] + ab[1] * ab[1]);

	if (t < 0) {
		return (ap[0] * ap[0] + ap[1] * ap[1]);
	} else if (t > 1) {
		const bp = [p[0] - b[0], p[1] - b[1]];
		return (bp[0] * bp[0] + bp[1] * bp[1]);
	} else {
		const projection = [a[0] + ab[0] * t, a[1] + ab[1] * t];
		const diff = [p[0] - projection[0], p[1] - projection[1]];
		return (diff[0] * diff[0] + diff[1] * diff[1]);
	}
}

//根据坐标获取地理信息
const getAdressInfoByCoordinate = function(coordinate) {
	return axios.post('/monitor/api/map/dataService_coordinateToAddressService1', {
		roundLocation: coordinate.join(',')
	});
}

// 经纬度格式化
function fmtLonLat([longt, ltat]) {
	const mapSource = getMapSource()
	return mapSource === 'amap' ? ol.proj.fromLonLat([longt, ltat]) : [longt, ltat];
}

// 取地图类型
function getMapSource() {
	return localStorage.getItem('mapSource') || 'tmap';
}

// 切换地图
function changeMapSource(source) {
	localStorage.setItem('mapSource', source);
	location.reload()
}